<template lang="pug">
  .m-content
    .title 云主机
    .main
      .searchs
        el-row(:gutter="10")
          el-col(:span="5")
            .flex-block
              .name 归属地市
              el-select.select.active( v-model="postConditions.areaCode" @change="query")
                el-option(v-for="item in areaCodes" :key="item.value" :label="item.label" :value="item.value")
          el-col(:span="5")
            .flex-block
              .name 状态
              el-select.select( v-model="postConditions.powerState" @change="query")
                el-option(v-for="item in powerState" :key="item.value" :label="item.label" :value="item.value")
          el-col(:span="6")
            .flex-block
              .name 创建时间
              el-date-picker(
                v-model="datetimerange"
                type="datetimerange"
                value-format="timestamp"
                start-placeholder="时间段(起)"
                end-placeholder="时间段(止)")
          el-col(:span="6")
            .searchTypeInput
              el-input( placeholder="bizid、成员/组合接入号、云主机名称" prefix-icon="el-icon-search" v-model="postConditions.keyword"  @keyup.enter.native="filterConditions")
      .operation
        el-button(type="primary" icon="iconfont icon-daochu") 导出
      .host-table
        tr-table(:data="tableData" :columns="columnsData" :filterWidth="80")
          template(slot-scope="scope")
            el-button(type="text" icon="iconfont icon-kaiji" @click="turnon(scope.row)") 开机
            el-button(type="text" icon="iconfont icon-guanji" @click="turnoff(scope.row)") 关机
            el-button(type="text" icon="iconfont icon-zhongzhi " @click="reset(scope.row)") 重置OS
            //- el-button(type="text" icon="iconfont icon-tongbu" @click="reload(scope.row)") 同步
      Pagination(:total="total" :page.sync="listQuery.page_no" :limit.sync="listQuery.page_size" @pagination="query" )
</template>
<script>
import { areaCodes, powerState, alertMessage } from '@/utils/config'
import { queryVms, shutdown, startup, restos, fetchPowerState } from '@/api/resource'
import { compose, columnLabel, isEmpty, memoize, formatArr, getlabel, isArrLength, isNull } from '@/utils/index'
import TrTable from '@/components/table/index.js'
import Pagination from '@/components/Pagination'

// 状态

const defaulConditions = {
  areaCode: 'ALL', // 归属地市
  powerState: 'ALL', // 状态
  keywordType: 'ALL', // 查询类型key
  keyword: '', // 查询类型value,
  startTime: '',
  endTime: ''
}
export default {
  data () {
    return {
      postConditions: Object.assign({}, defaulConditions),
      datetimerange: [],
      areaCodes,
      powerState,
      total: 0,
      tableData: [],
      columnsData: [
        { prop: 'platformId',
          label: '成员接入号',
          formatter: () => ({ class: 'title' }),
          handleClick: this.getDetail,
          hidden: true },
        { prop: 'combinationTag', label: '组合接入号' },
        { prop: 'userId', label: 'bizid' },
        { prop: 'areaCode', label: '归属地市', formatter: this.getAreaCodeLabel },
        { prop: 'name', label: '云主机名称' },
        { prop: 'powerState', label: '状态', formatter: this.getPowerStateLabel },
        { prop: 'standard', label: '规格', formatter: (key, row) => ({ label: `${row.vcpus}C ${row.memory}G` }) }, // 1C1G
        { prop: 'refNetwork', label: '公网带宽', formatter: (key, row) => ({ label: (row[key] && `${row[key].bandwidth}Mbps`) || '0Mbps' }) },
        { prop: 'refNetwork1', label: 'IP', formatter: this.getIps },
        { prop: 'refSystemDisk', label: '系统磁盘', formatter: (key, row) => ({ label: `${row[key].size}GB ${row[key].type}` }) },
        { prop: 'refAttachedDisk', label: '数据磁盘', formatter: this.getAttachedDiskLabel },
        { prop: 'osName', label: '操作系统名称', unchecked: true },
        { prop: 'remoteUpdateAt', label: '更新时间', formatter: this.formatterAt },
        { prop: 'remoteExpireAt', label: '过期时间', formatter: this.formatterAt }
      ],
      listQuery: {
        page_no: 1,
        page_size: 10
      }
    }
  },
  components: {
    TrTable,
    Pagination
  },
  watch: {
    datetimerange (val) {
      this.query()
    }
  },
  mounted () {
    this.query()
  },
  methods: {
    query () {
      this.queryVmsList(this.listQuery, this.postConditions)
    },
    getDetail (row) {
      this.$router.push('/resource/ResourceMain/HostCloud/details/' + row.id)
    },
    formatterAt (prop, row) {
      return compose(columnLabel, formatArr.bind(null, this.$moment), isEmpty)(row[prop])
    },
    getPowerStateLabel (prop, row) {
      this.powerObj = this.powerObj ||
        compose(columnLabel, memoize(getlabel.bind(null, powerState)), isEmpty)
      return this.powerObj(row[prop])
    },
    getAreaCodeLabel (prop, row) {
      this.codeObj = this.codeObj ||
        compose(columnLabel, memoize(getlabel.bind(null, areaCodes)), isEmpty)
      return this.codeObj(row[prop])
    },
    getIps (prop, row) {
      let accessIpV4 = row.refNetwork && row.refNetwork.accessIpV4
      let privateIps = row.refNics.map(d => `${d.ipV4}私网`)
      return columnLabel([accessIpV4 && `${accessIpV4}公网`, ...privateIps])
    },
    getAttachedDiskLabel (prop, row) {
      let ret = row[prop].map(v => {
        return `${v.size}GB ${v.type}`
      })
      return compose(columnLabel, isArrLength)(ret)
    },
    filterConditions () {
      const value = this.postConditions.keyword
      if (/^\d{12,}$/.test(value)) {
        this.postConditions.keywordType = 'BIZID'
      }

      if (/^\d+_[A-Z]{3,4}\d+$/.test(value)) {
        this.postConditions.keywordType = 'PLATFORM_ID'
      }

      if (/^\d+[a-z]{3,4}\d+$/.test(value)) {
        this.postConditions.keywordType = 'PLATFORM_ID,COMBINATION_TAG'
      }
      this.listQuery.page_no = 1
      this.query()
    },
    turnon (row) {
      this.$Qconfirm('确定开机吗', '提示').then(() => {
        let { id } = row
        startup.call(this, id).then(res => {
          alertMessage.call(this, res.data, res.data.statusCode, '开机指令下发成功')
          this.query()
        })
      })
    },
    turnoff (row) {
      this.$Qconfirm('确定关机吗', '提示').then(() => {
        let { id } = row
        shutdown.call(this, id).then(res => {
          alertMessage.call(this, res.data, res.data.statusCode, '关机指令下发成功')
          this.query()
        })
      })
    },
    reset (row) {
      this.$Qconfirm('确定重置OS吗', '提示').then(() => {
        let { id } = row
        restos.call(this, id).then(res => {
          alertMessage.call(this, res.data, res.data.code, '重置OS指令下发成功')
          this.query()
        })
      })
    },
    queryVmsList (params, data) {
      if (isNull(this.datetimerange)) {
        data.startTime = ''
        data.endTime = ''
      } else if (this.datetimerange.length) {
        data.startTime = this.datetimerange[0]
        data.endTime = this.datetimerange[1]
      }

      queryVms.call(this, params, data).then(res => {
        let data = res.data && res.data.data
        this.total = res.data.total_count
        let states = ['NB_STARTING', 'NB_STOPPING']
        let updateIds = data.filter(v => states.includes(v.powerState)).map(d => d.id)
        this.updateListPowerState(updateIds)
        this.tableData = data
      })
    },
    updateListPowerState (id) {
      if (id.length === 0) return
      let data = { vmIds: id }
      setTimeout(() => {
        fetchPowerState.call(this, data).then(res => {
          let { afresh, disposal } = res.data
          // 更改状态
          for (let i = 0; i < this.tableData.length; i++) {
            for (let v = 0; v < disposal.length; v++) {
              if (this.tableData[i].id === disposal[v].id) {
                this.tableData[i].powerState = disposal[v].powerState
              }
            }
          }
          // 重新查询
          let afreshID = afresh.map(v => v.id)
          this.updateListPowerState(afreshID)
        })
      }, 15000)
    }
  }
}
</script>
<style lang="stylus" scoped>
.m-content
  .main
    padding 15px 20px
    .searchs
      .iconfont
        display inline-block
        margin-right 3px
      .searchTypeInput
        line-height 1
        margin-left 28px
        .el-input
          width 220px
    .operation
      margin 15px 0 0 0
    .host-table
      >>>
        td
          div
            font-size 12px
            &.title
              color #1f60bd
              cursor pointer
          .el-button+.el-button
            margin-left 0
</style>
